// 导入 express 模块
const express = require("express");
// 导入 session 模块
const session = require("express-session");
// 导入 connect-mongo 模块
const mongo = require("connect-mongo");

// 创建应用对象
const app = express();

// 设置中间件
var hss = session({
  name: "sid",
  secret: "techfengs",
  saveUninitialized: false,
  resave: true,
  store: mongo.create({
    mongoUrl: "mongodb://127.0.0.1:27017/bilibili",
  }),
  cookie: {
    httpOnly: true,
    maxAge: 1000 * 60 * 5,
  },
});

app.use(hss);

// 路由规则
app.get("/", (req, res) => {
  res.send("Homepage");
});

app.get("/login", (req, res) => {
  if (req.query.username == "admin" && req.query.password == "admin") {
    req.session.username = req.query.username;
    res.send("登录成功");
  } else {
    res.send("登录失败");
  }
});

app.get("/cart", (req, res) => {
  if (req.session.username) {
    res.send(`购物车页面，欢迎您 ${req.session.username}`);
  } else {
    res.send("请先登录，才能使用购物车");
  }
});

// 监听端口，启动服务
app.listen(3000, () => {
  console.log("express创建session：服务已经启动……");
});
